package hibernate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;






















import modelo.*;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class HibernateDaoMateria {
	private static HibernateDaoMateria instancia;
	private static SessionFactory sf;
	
	public static HibernateDaoMateria getInstancia(){
		if(instancia == null) {
			sf = HibernateUtil.getSessionFactory();
			instancia = new HibernateDaoMateria();
		}
		return instancia;
	}
	
	@SuppressWarnings({ "rawtypes" })
	public List<Docente> traerDocentesDeMateria(Materia m)
	{
		Session session = sf.openSession();
		int id=m.getId();
		List<Docente> d = new ArrayList<Docente>();
		
		Iterator i =session.createQuery("select md.dni,md.nombre,md.apellido From Materia m join m.docentes md where m.Id_Materia=(:id) ").setParameter("id", id).iterate();
		
		while(i.hasNext())
		{
			Object[] tupla = (Object[]) i.next();
			int dni = (int) tupla[0];
			String nombre = (String) tupla[1];
			String apellido = (String) tupla[2];
			
			Docente docente = new Docente(dni, nombre, apellido);
			d.add(docente);
		}
		return d;
	}
	
	
	public String[] traerMaterias(){
		Session session= sf.openSession();
	
		long cant = (long) session.createQuery("select count(*) from Materia").uniqueResult();
		
		@SuppressWarnings("rawtypes")
		Iterator i = session.createQuery("select m.nombre From Materia m").iterate();
		
		String mate[] = new String[(int) cant];
		int j=0;
		while(i.hasNext())
		{
			String tupla = (String) i.next();
			mate[j]= (String) tupla;
			j++;
		}
		session.close();
		return mate;
		
	}
	
	public Materia buscarMateria(int id){
		Session session = sf.openSession();
		Materia m = (Materia) session.createQuery("From Materia m where m.Id_Materia = (:id)").setParameter("id",id).uniqueResult();
		session.close();
		return m;
	}
	
	public Materia buscarMateriaPorNombre(String nom)
	{
		Session session = sf.openSession();
		int id = (int) session.createQuery("select m.Id_Materia from  Materia m where m.nombre=(:nom)").setParameter("nom",nom).uniqueResult();
		Materia m = buscarMateria(id);
		session.close();
		return m;
	}
	
	public void grabarMateria(Materia m){
		Session session = sf.openSession();
		session.beginTransaction();
		session.save(m);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}
	public void eliminarMateria(int id){
		Session session =  sf.openSession();
		session.beginTransaction();
		Materia m = buscarMateria(id);
		session.delete(m);
		session.getTransaction().commit();
		session.close();		
	}
	public void modificarMateria(Materia m){
		Session session = sf.openSession();
		session.update(m);
		session.close();
	}
}
